<template>
	<el-card shadow="never">
		<el-form :inline="true">
			<el-form-item>
				<el-button type="primary" @click="handleOrg()">新增</el-button>
			</el-form-item>
		</el-form>
        
		<el-table
            v-loading="loading"
            :data="orgList"
            row-key="id"
            style="width: 100%"
            border>
			<el-table-column
                prop="name"
                label="名称"
                header-align="center">
            </el-table-column>
			<el-table-column
                prop="parentName"
                label="上级"
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                prop="sort"
                label="排序"
                header-align="center"
                align="center">
            </el-table-column>
			<el-table-column
                label="操作"
                header-align="center"
                align="center"
                width="150">
				<template #default="scope">
					<el-button link type="primary" @click="handleOrg(scope.row.id)">修改</el-button>
					<el-button link type="primary" @click="deleteOne(scope.row.id, 'id')">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

        <!-- 新增/修改组件 -->
        <OrgDlg ref="orgDlgRef" @refresh="getOrgList" />

    </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { orgStore } from '@/store/org'
import { storeToRefs } from 'pinia'
import OrgDlg from './org_dlg.vue'

const loading = ref(false)
const useOrgStore = orgStore()
const { orgList } = storeToRefs(useOrgStore) // 使用storeToRefs解构

onMounted(() => {
    getOrgList()
})

// 获取机构列表
const getOrgList = async () => {
  try {
    loading.value = true
    await useOrgStore.getOrgList()
  } catch (error) {
    console.error('获取机构列表失败:', error)
  } finally {
    loading.value = false
  }
}

const orgDlgRef = ref(null)
const handleOrg = (id) => {
    if (id) {
        // 修改模式
        orgDlgRef.value.init(id)
    } else {
        // 新增模式
        orgDlgRef.value.init()
    }
}

const deleteOne = async (id, field) => {
    try {
        await ElMessageBox.confirm('确定要删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await useOrgStore.deleteOrg({ [field]: id })
        ElMessage.success('删除成功')
        getOrgList() // 刷新列表
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除失败')
        }
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-table) {
    --el-table-border-top-color: #eee !important;  /* 修改边框颜色 */
}
</style>